package com.hcc.flow.server.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcc.flow.server.model.common.AuthenticationBean;

/**
 * @author 韩长长 
 * @version
 * 
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	private static final Logger log = LoggerFactory.getLogger("adminLogger");
	

	/*
	 * @Autowired private AuthenticationEntryPoint failureHandler;
	 */

	@SuppressWarnings("finally")
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		log.debug("----------000----" + request.getContentType() + "\n");
		// attempt Authentication when Content-Type is json
		if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
				|| request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {

			// use jackson to deserialize json
			ObjectMapper mapper = new ObjectMapper();
			UsernamePasswordAuthenticationToken authRequest = null;

			try (InputStream is = request.getInputStream()) {

				String content = new BufferedReader(new InputStreamReader(is)).lines()
						.collect(Collectors.joining(System.lineSeparator()));
				if (content.contains("param") && content.contains("{")) {
					JSONObject jsonObject = JSONObject.parseObject(content);
					content = jsonObject.get("param").toString();
				}
				// log.debug("----------"+content+"\n");
				//if (!StringUtilsV2.isBlank(encryptProperties.getKey())) {
					//throw new NullPointerException("请配置spring.encrypt.key");
				//}
				// 解密
				String desCon = content;
				if (desCon != null && !desCon.isEmpty()) {

					InputStream isNew = new ByteArrayInputStream(desCon.getBytes());
					// 转化成认证对象
					AuthenticationBean authenticationBean = mapper.readValue(isNew, AuthenticationBean.class);
					if (authenticationBean != null) {
						authRequest = new UsernamePasswordAuthenticationToken(authenticationBean.getUsername(),
								authenticationBean.getPassword());
					}

				} else {
					authRequest = new UsernamePasswordAuthenticationToken("", "");
				}

			} catch (Exception e) {
				e.printStackTrace();
				authRequest = new UsernamePasswordAuthenticationToken("", "");
			} finally {

				setDetails(request, authRequest);

				return this.getAuthenticationManager().authenticate(authRequest);
			}
		}

		// transmit it to UsernamePasswordAuthenticationFilter
		else {
			return super.attemptAuthentication(request, response);
		}
	}

}
